var product = {
    config : {
        'pg_start' : 0, //默认当前第一页
    },
    init : function(){
        product.enshrine();
        product.reviews();
    },
    enshrine : function(){
        if ($('.view-product-enshrine').size() > 0) {
            var dataSid = $('.view-product-enshrine').attr('data-sid');
            $.ajax({
                type: 'get',
                async: true,
                dataType : 'json',
                url: hostUrl()+'scenic/info/enshrine',
                data: {sid : dataSid},
                success: function(data) {
                    if (data.status) {
                        $('.view-product-enshrine').addClass('active');
                    }
                }
            });
            
            $('.view-product-enshrine').click(function(){
                var $this = $(this);
                var active = $this.hasClass('active');
                $.ajax({
                    type: 'post',
                    async: true,
                    dataType : 'json',
                    url: hostUrl()+'scenic/info/setEnshrine',
                    data: {sid : dataSid, active : active},
                    beforeSend : function (evt, request, settings) {
                    },
                    success: function(data) {
                        if (data.status) {
                            if (active) {
                                $this.removeClass('active');
                            } else {
                                $this.addClass('active');
                            }
                            myalert(data.messages);
                        } else {
                            if (data.messages.indexOf('ttp://') != -1) {
                                window.location.href = data.messages;
                            } else {
                                myalert(data.messages);
                            }
                        }
                    }
                });
            });
        }
    },
    
    reviews : function(){
        $('#my-scrollspy').scrollspy({
            animation: 'fade',
            delay: 500
        });
        $('#my-scrollspy').on('inview.scrollspy.amui', function() {
            var pgStart = product.config['pg_start'] + parseInt(1);
            var dataSid = $(this).attr('data-sid');
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: hostUrl() + 'scenic/info/getReviews',
                data: {pg : pgStart, sid : dataSid},
                beforeSend : function (evt, request, settings) {
                    //$('html').css('overflowY', 'hidden'); //隐藏滚动条
                },
                success: function(data) {
                    if (data.num < 10) {
                        $('#my-scrollspy').addClass('am-hide').next('.no-more').removeClass('am-hide');
                        $('#data-review-info').append(data.html);
                    } else {
                        product.config['pg_start'] = product.config['pg_start'] + parseInt(1)
                        $('#data-review-info').append(data.html);
                    }
                    $('img.lazy').lazyload();
                }
            });
        });
    },
}

$(function(){
    product.init(); //订单页面
});


/* 日历  */
var calendar ={ 
    data:[],  //{id:'1',date:'2016-3-22',price:'30000.00'}

    config:{
        noteYear:  null,                //年
        noteMonth: null,                //月
        noteDay:   null,                //日
        active:       null,                //选定日期
        feast:[
            {time:'1-1',name:'元旦'},    //节假日
            {time:'2-14',name:'情人节'},
            {time:'3-8',name:'妇女'},
            {time:'5-1',name:'劳动'},
            {time:'6-1',name:'儿童'},
            {time:'9-10',name:'教师'},
            {time:'10-1',name:'国庆'}
        ]
    },
    main:function(name,days){                //初始化
        var _this = this,
            year = _this.today.year(),
            month = _this.today.month(),
            day = _this.today.day();

        _this.config.noteYear = year;
        _this.config.noteMonth = month;
        _this.config.noteDay = day;
        _this.config.active = days;

        var now = _this.tostring(year,month);
        _this.noteDown();
        var next = _this.tostring(year,month+1);
        $(name).html(now+next);
    },
    tostring:function(year,month){
        var _this = this,
            day = _this.days(year,month),
            week = _this.weeks(year,month,1),
            date=1,
            dataDom = '<div class="ord-year">'+
                            year+'年'+month+'月'+
                      '</div>'+
                      '<dl class="am-cf">'+
                          '<dt>日</dt>'+
                          '<dt>一</dt>'+
                          '<dt>二</dt>'+
                          '<dt>三</dt>'+
                          '<dt>四</dt>'+
                          '<dt>五</dt>'+
                          '<dt>六</dt>';
        for(i=0;i<42;i++){
            if(week<=i&&date<=day){
                var feast = _this.feast(year,month,date),
                    fodur = _this.forData(date);
                if(!feast){
                    feast=date;
                }
                var price = '<dd>'+
                                '<h6>'+ feast +'</h6>'+
                            '</dd>';
                if(fodur.id>0){
                    var week = _this.weeks(year,month,date);
                    var active ='"valid"';
                    if(fodur.active){
                        active= '"valid active"';
                    }
                    price='<dd class='+active+
                                 'data-time='+year+'-'+month+'-'+date+' '+
                                 'data-price='+fodur.price+' '+
                                 'data-id='+fodur.id+' '+
                                 'data-week='+week
                              +'>'+
                              '<h6>'+ feast +'</h6>'+
                              '<i>'+
                                 '<span>￥</span>'+ Math.floor(fodur.price)+
                              '</i>'+
                          '</dd>';
                }
                dataDom += price;
                date++;
            }else{
                var time ='<dd></dd>';
                dataDom +=time;
            }
        }
        dataDom +='</dl>';
        return dataDom;
    },
    forData:function(time){            //遍历json
        var _this = this,
            params = {price:0,id:0,active:false};
        time = _this.config.noteYear.toString()+'-'+
               _this.config.noteMonth.toString()+'-'+
               time.toString();

        for(var i=0,num=_this.data.length;i<num;i++){
            if(_this.data[i].date===time){
                if(_this.config.active===time){
                    params.active=true;
                }
                params.price = _this.data[i].price;
                params.id = _this.data[i].id;
                break;
            }
        }

        return params;
    },
    feast:function(year,month,day){
        var _this = this,
            feastData = month+'-'+day,
            today = _this.today.year()+'-'+_this.today.month()+'-'+_this.today.day(),
            compare = year+'-'+month+'-'+day,
            feast = false;

        for(var i=0,num=this.config.feast.length;i<num;i++){
            if(_this.config.feast[i].time===feastData){
                feast = _this.config.feast[i].name;
                break;
            }else if(today===compare){
                feast ='今天';
            }
        }
        return feast;
    },
    noteDown:function(){            //下个月
        var _this = this,
            month = _this.config.noteMonth;

        if(month===12){
            _this.config.noteMonth=1;
            _this.config.noteYear++;
        }else{
            _this.config.noteMonth++;
        }
    },
    today:{                            //今天
        date:new Date(),
        year:function(){
            return this.date.getFullYear();
        },
        month:function(){
            return this.date.getMonth()+1;
        },
        day:function(){
            return this.date.getDate();
        }
    },
    days:function(year,month){        //返回某个月的总天数
        month=parseInt(month,10);
        var day=new Date(year,month,0);
        return day.getDate();
    },
    weeks:function(year,month,day){        //计算某个月的第一天是星期几
        month=month-1;
        var week=new Date(year,month,day);
        return week.getDay();
    }
}

var checkout = {
    config : {
        'buy_scenic_id' : 0, //当前操的景区编号
        'buy_goods_id' : 0, //当前操的门票编号
        'buy_num' : 1,      //当前操的门票数量
    },
    init : function(){
        $this = this;
        $this.config.buy_scenic_id = $('input[name=scenicId]').val(); //初始化
        $this.config.buy_goods_id = $('input[name=ticketId]').val(); //初始化
        checkout.orderTicket();
        checkout.orderTotal();
        checkout.ticketPop();
        checkout.selectedTicket();
        checkout.deleteTicket();
        checkout.pumAdd();
        checkout.pumMinus();
        checkout.pumInput();
        checkout.orderBonus();
        checkout.orderSubmit();
        checkout.oftenVisitor(); //选择常用联系人
        checkout.getTicketDate();
    },
    
    selectedTicket : function(){ //选中指定门票
        $('#ticket-pop-add').on('click', '.vive-book a.vive-rese:not(.active)', function(event){
            $(this).addClass('active'); //防止多次点击
            $this.config.buy_goods_id = $(this).attr('data-goods-id');
            checkout.orderTicket();
            var fristDelete = $('.order-ticket-info dl dt');

            if (fristDelete.size() > 1 && fristDelete.first().children('a.ord-delete').size() <= 0) {
                fristDelete.first().append('<a href="javascript:;" class="ord-delete"><i class="iconfont">&#xe611;</i></a>');
            }

            checkout.orderTotal();
            checkout.left('.page-1', 'show-4');
            event.stopPropagation();
        });
    },
    
    deleteTicket : function(){ //移除指定门票
        $('.order-ticket-info').on('click','a.ord-delete',function(event){
            $('#my-confirm').modal({
                relatedTarget: this,
                onConfirm: function() {
                    $(this.relatedTarget).parents('dl').remove();
                    if ($('.order-ticket-info dl dt').size() < 2) {
                        $('.order-ticket-info dl dt a.ord-delete').remove();
                    }
                    $('.ord-page').height($('.page-1').height());
                    checkout.orderTotal();
                },
                onCancel: function(){}
            });
            event.stopPropagation();
        });
    },
    
    orderTicket : function(){ //加载预定门票详情
        if ($('.scenic-ticket-form').size() > 0) {
            $.ajax({
                type: 'post',
                dataType : 'json',
                async : false,
                url: hostUrl() + 'scenic/checkout/orderTicket',
                data: {scenicId : $this.config.buy_scenic_id, ticketId : $this.config.buy_goods_id},
                beforeSend : function (evt, request, settings) {
                    
                },
                complete : function (evt, request, settings) {
                    // body...
                },
                success: function(data) {
                    if (data.status) {
                        $('.order-ticket-info').append(data.messages);
                        if ($('.order-ticket-info dl dt').size() < 2) {
                            $('.order-ticket-info dl dt a.ord-delete').remove();
                        }
                    } else {
                        if (data.messages) {
                            window.location.href = data.messages;
                        } else {
                            $('a[href="#ticket-pop-add"]').trigger('click');
                        }
                    }
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
        }
    },
    
    orderTotal : function(){ //加载预定门票支付总金额
        if ($('.scenic-ticket-form').size() > 0) {
            $.ajax({
                type: 'post',
                dataType : 'json',
                url: hostUrl() + 'scenic/checkout/orderTotal',
                data: $('.scenic-ticket-form').serialize(),
                beforeSend : function (evt, request, settings) {
                },
                complete : function (evt, request, settings) {
                    // body...
                },
                success: function(data) {
                    if (data.status) {
                        var ticketTotal = data.ticketTotal[$this.config.buy_goods_id]
                        $('.ticketTotal-'+$this.config.buy_goods_id).text(ticketTotal);
                        $('.page-1 .ord-coin .orderBouns').html(data.orderBouns);
                        $('.page-1 .ord-coin [name=order_bouns]').val(data.orderBouns);
                        $('.orderTotal').text(data.orderTotal);
                    } else {
                        myalert(data.messages);
                    }
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
        }
    },
    
    ticketPop : function(){ //弹框门票详情
        $('.scenic-ticket-form').on('click','.ord-again',function(event){
            $.ajax({
                type: 'post',
                dataType : 'html',
                url: hostUrl() + 'scenic/checkout/ticketPop',
                data: $('.scenic-ticket-form').serialize(),
                beforeSend : function (evt, request, settings) {
                    //$('html').css('overflowY', 'hidden'); //隐藏滚动条
                },
                success: function(data) {
                    $('#ticket-pop-add').html(data);
                    checkout.right('.page-4','show-4');
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        $('.page-ye').on('click', '.ord-return', function(event){
            var show = $(this).data('return');
            if (show === 'show-3') {
                checkout.remove();
            }
            checkout.left('.page-1', show);
            event.stopPropagation();
        });
        $('#ticket-pop-add').on('click', '.modal-ticket-descript', function(event) {
            var obj = $(this);
            $.ajax({
                type: 'post',
                dataType : 'html',
                url: hostUrl() + 'scenic/checkout/ticketDescript',
                data: {'goods_id' : obj.attr('data-goods-id')},
                beforeSend : function (evt, request, settings) {
                    $('#modal-ticket-descript').removeClass('hide-loading').modal();
                },
                success: function(data) {
                    $('#modal-ticket-descript').addClass('hide-loading').children('.ticket-contents').html(data);
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        $('#modal-ticket-descript').on('click', 'a.am-close', function(){
            $('#modal-ticket-descript').modal('close');
        });
    },
    
    getTicketDate : function(){
        $('.ord-page').height($('.page-1').height());
        $('.ord-dl').on('click','.ord-deta',function(event){
            var obj = $(this);
            $.ajax({
                type: 'post',
                dataType : 'json',
                url: hostUrl() + 'scenic/checkout/getTicketDate',
                data: {'goods_id' : obj.attr('data-goods-id')},
                beforeSend : function (evt, request, settings) {
                    //$('html').css('overflowY', 'hidden'); //隐藏滚动条
                },
                success: function(data) {
                    calendar.data = data;
                    var days = obj.find('.ord-time').text();
                    calendar.main('.ord-calendar', days);
                    checkout.right('.page-2','show-2');
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        
        if ($('.ord-calendar').size()>0) {
            $('.ord-calendar').on('click', '.valid', function(event){
                var dataId   = $(this).attr('data-id');
                var dataTime = $(this).data('time');
                var dataWeek = $(this).data('week');
                var dataHtml = '<h6 class="flex">'+
                                   '<p class="ord-time">'+dataTime+'</p>'+
                                   '<span>'+'星期'+'日一二三四五六'.charAt(dataWeek)+'</span>'+
                               '</h6>';
                $('#ticket-date-'+dataId).html(dataHtml);
                $('#buy-date-'+dataId).val(dataTime);
                checkout.left('.page-1','show-2');
                event.stopPropagation();
            });
        }
    },
    
    pumAdd : function(){ //门票数量加计算
        $('.order-ticket-info').on('click', '.num-add', function(event){
            var input=$(this).prev('input');
            var max =input.data('max');
            var input_text=parseInt(input.val());
            $this.config.buy_goods_id = input.attr('data-goods-id');
            if (!(input_text===max)) {
                input.val(input_text+1);
                checkout.orderTotal();
            } else {
                alertMessage('库存不足或限制购买数量');
            }
            event.stopPropagation();
        });
    },
    
    pumMinus : function(){ //门票数量减计算
        $('.order-ticket-info').on('click', '.num-minus', function(event){
            var input=$(this).next('input');
            var min =input.data('min');
            var input_text=parseInt(input.val());
            $this.config.buy_goods_id = input.attr('data-goods-id');
            if (!(input_text==min||input_text<0)) {
                input.val(input_text-1);
                checkout.orderTotal();
            } else if (input_text > min) {
                alertMessage('限制最低购买数量');;
            }
            event.stopPropagation();
        });
    },
    
    pumInput : function(){ //门票数量修改计算
        $('.order-ticket-info').on('blur', '.num-input', function(event){
            var input = parseInt($(this).val(),10);
            var min = $(this).data('min');
            var max = $(this).data('max');
            $this.config.buy_goods_id = $(this).attr('data-goods-id');
            if (isNaN(input) || input===0) {
                $(this).val(min);
            } else if (input>max) {
                $(this).val(max);
            } else {
                $(this).val(input);
            }
            checkout.orderTotal();
            event.stopPropagation();
        });
    },
    
    orderBonus : function(){ //游币支付是否正常
        $('.scenic-ticket-form').on('click','.ord-coin',function(event){
            var icon = $(this).find('.check-icon');
            if (icon.hasClass('active')) {
                icon.removeClass('active');
                icon.prev('input').prop('checked', false);
            } else {
                icon.addClass('active');
                icon.prev('input').prop('checked', true);
            }
            checkout.orderTotal();
            event.stopPropagation();
        });
    },
    
    oftenVisitor : function(){
        //选择常用联系人
        $('.scenic-ticket-form .ord-form, #scan-scenic-ticket-form .ord-form').on('click', '.go-icon', function(event){
            $.ajax({
                type: 'post',
                dataType : 'html',
                url: hostUrl() + 'scenic/checkout/oftenVisitor',
                data: $('.scenic-ticket-form').serialize(),
                beforeSend : function (evt, request, settings) {
                    //$('html').css('overflowY', 'hidden'); //隐藏滚动条
                },
                success: function(data) {
                    $('#oftenVisitor').html(data);
                    checkout.right('.page-3', 'show-3');
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        //选择常用联系人或者编辑常用联系人
        $('#oftenVisitor').on('click', 'ul li', function(event){
            var object = eval('('+$(this).data('user')+')');
            if ($(this).parents('.go-people').hasClass('edit')) {
                $('#visitor-modify-alert input[name=visitor_id]').val(object.visitor_id);
                $('#visitor-modify-alert input[name=visitor_name]').val(object.visitor_name);
                $('#visitor-modify-alert input[name=mobile_phone]').val(object.mobile_phone);
                $('#visitor-modify-alert input[name=visitor_sfz]').val(object.visitor_pin);
                $('#visitor-modify-alert input[name=sex]').val(object.sex);
                $('#visitor-modify-alert input[name=type]').val(object.type);
                $('#visitor-modify-alert').modal();
            } else {
                $(this).addClass('active').siblings('li').removeClass('active');
                if ($('#scan-scenic-ticket-form').size() > 0) {
                    $('#scan-scenic-ticket-form input[name=visitor_name]').val(object.visitor_name);
                    $('#scan-scenic-ticket-form input[name=visitor_sfz]').val(object.visitor_pin);
                    $('#scan-scenic-ticket-form input[name=visitor_telephone]').val(object.mobile_phone);
                } else {
                    $('.scenic-ticket-form input[name=visitor_name]').val(object.visitor_name);
                    $('.scenic-ticket-form input[name=visitor_sfz]').val(object.visitor_pin);
                    $('.scenic-ticket-form input[name=visitor_telephone]').val(object.mobile_phone);
                }
                checkout.left('.page-1','show-3');
            }
            event.stopPropagation();
        });
        //新增联系人
        $('.add-often-visitor').click(function(){
            $('#visitor-modify-alert input[name=visitor_id]').val('');
            $('#visitor-modify-alert input[name=visitor_name]').val('');
            $('#visitor-modify-alert input[name=mobile_phone]').val('');
            $('#visitor-modify-alert input[name=visitor_sfz]').val('');
            $('#visitor-modify-alert').modal();
        });
        $('#visitor-modify-alert').on('click', '.alert-button', function(event){
            $.ajax({
                type: 'post',
                dataType : 'json',
                url: hostUrl() + 'scenic/checkout/oftenVisitorModify',
                data: $('#visitor-modify-alert form').serialize(),
                beforeSend : function (evt, request, settings) {
                },
                success: function(data) {
                    if (data.status) {
                        $('#oftenVisitor').html(data.messages);
                        myalert('保存成功');
                        $('.go-button .return-cancel').trigger('click');
                        $('#visitor-modify-alert').modal('close');
                    } else {
                        myalert(data.messages);
                    }
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        //关闭修改或编辑弹框
        $('#visitor-modify-alert').on('click', '.alert-return', function(event){
            $('#visitor-modify-alert').modal('close');
            event.stopPropagation();
        });
        //切换修改模式
        $('.go-button').on('click', '.return-edit', function(event){
            $(this).parent().addClass('active');
            $('.go-people').addClass('edit');
            event.stopPropagation();
        });
        //还原选择模式
        $('.go-button').on('click', '.return-cancel', function(event){
            checkout.remove();
            event.stopPropagation();
        });
    },
    
    right : function(pageName, showName){
        $('.ord-page').addClass(showName).height($(pageName).height());
        $('.ord-foot').hide();
        $('html, body').scrollTop(0);
    },
    left : function(pageName, showName){
        $('.ord-page').removeClass(showName).height($(pageName).height());
        $('.ord-foot').show();
        $('html, body').scrollTop(0);
    },
    remove : function(){
        $('.go-button').removeClass('active');
        $('.go-people').removeClass('edit');
    },
    
    orderSubmit : function(){ //提交订单操作
        $('.scenic-ticket-form').submit(function(event){
            var obj = $('.ord-foot button[type=submit]');
            $.ajax({
                type: 'post',
                async: true,
                dataType : 'json',
                url: hostUrl()+'scenic/checkout/orderSubmit',
                data: $('.scenic-ticket-form').serialize(),
                beforeSend: function() {
                    obj.text('加载中...').attr('disabled', true);
                },
                success: function(data) {
                    if (data.status) {
                        window.location.href = data.messages;
                    } else {
                        myalert(data.messages);
                        obj.text('重新提交').removeAttr('disabled');
                    }
                }
            });
            event.preventDefault()
        });
        
        $('.ord-foot button[type=submit]').click(function(){
            $('.scenic-ticket-form').trigger('submit');
        });
    }
};
$(function(){
    checkout.init(); //订单页面
});

payment = {
    init : function(){
        payment.paymethod();
        payment.balancePay();
    },
    paymethod : function(){ //支付界面
        if ($('.pay-order-scenic').size()>0) {
            $('.pay-total').on('click', '.pay-open, .pay-stop', function(event){
                if ($('.pay-ol').hasClass('pay-hidden')) {
                    $('.pay-ol').removeClass('pay-hidden');
                } else {
                    $('.pay-ol').addClass('pay-hidden');
                }
                event.stopPropagation();
            });
            $('.pay-mode').on('click', 'dd', function(event){
                var other = $(this).siblings();
                $(this).addClass('active').children('.pay-radio').prop('checked', true);
                other.removeClass('active').children('.pay-radio').prop('checked', false);
                event.stopPropagation();
            });
        }
    },
    balancePay : function(){ //余额支付过程
        $('.balance-pay-info').submit(function(event){
            var obj = $('.balance-pay-info button[type=submit]');
            $.ajax({
                type: 'post',
                async: true,
                dataType : 'json',
                url: hostUrl()+'scenic/payment/balancePay',
                data: $('.balance-pay-info').serialize(),
                beforeSend: function() {
                    var password = $('input[name=pay_pw]').val();
                    if (password == '' || password.length < 6) {
                        myalert('密码长度不能小于6位');
                        return false;
                    } else {
                        obj.text('加载中...').attr('disabled', true);
                    }
                },
                success: function(data) {
                    if (data.status) {
                        window.location.href = data.messages;
                    } else {
                        myalert(data.messages);
                        obj.text('重新提交').removeAttr('disabled');
                    }
                }
            });
            event.preventDefault()
        });
    }
};

$(function(){
    payment.init(); //订单支付页面
});
